iT邦幫忙

2021 iThome 鐵人賽

DAY 4
0

昨天把所有程式碼都寫在一起包括class與程式進入點main(),但這樣做有個缺點就是會暴露原始碼, C/C++算是一門很老的語言當時的風氣傾向保密細節只留下.h標頭檔展示類別的介面(interface of class)如下GradeBook.h,而實作會放在.cpp檔中先編譯好,這樣就可以避免使用者看到實作細節。

//GradeBook.h
#include <string> // class GradeBook uses C++ standard string class
using namespace std;

class GradeBook
{
public:
   GradeBook( string ); // constructor that initializes courseName
   void setCourseName( string ); // function that sets the course name
   string getCourseName(); // function that gets the course name
   void displayMessage(); // function that displays a welcome message   
   
private:
   string courseName; // course name for this GradeBook
}; 
//GradeBook.cpp
#include <iostream>
#include "GradeBook.h" // include definition of class GradeBook
using namespace std;

// constructor initializes courseName with string supplied as argument
GradeBook::GradeBook( string name )
{
   setCourseName( name ); // validate and store courseName
} 

void GradeBook::setCourseName( string name )
{
	
   if ( name.length() <= 25 ) // if name has 25 or fewer characters
      courseName = name; // store the course name in the object

   if ( name.length() > 25 ) // if name has more than 25 characters
   { 
      // set courseName to first 25 characters of parameter name
      courseName = name.substr( 0, 25 ); // start at 0, length of 25

      cout << "Name \"" << name << "\" exceeds maximum length (25).\n"
         << "Limiting courseName to first 25 characters.\n" << endl;
   } // end if
} 

string GradeBook::getCourseName()
{
   return courseName; // return object's courseName
} 

void GradeBook::displayMessage()
{
   // call getCourseName to get the courseName
   cout << "Welcome to the grade book for\n" << getCourseName()  
      << "!" << endl;
} 

上一篇
Day3
下一篇
Day5-如何超越Google
系列文
少年DevOps的C++奇怪漂流30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言